<?php

namespace Yi\Permission\Http\Controllers\miniprogram;

use App\Http\Controllers\Controller;
use Yi\Permission\Models\MiniprogramhUser;
use Illuminate\Http\Request;
use \Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Facades\JWTAuth;
use Auth;
use Illuminate\Support\Facades\Redis;
use App\Helper\AES;
use Illuminate\Support\Facades\Log;
use Yi\Permission\Models\Member;


class MiniprogramController extends Controller
{

    /**
     * 
     */
    public function oauth(Request $request)
    {
        $code = $request->input('code', '');
        $token_json = [];
        if ($code) {

            // if ($code == 'eee') {
            //     $token_data = [ "openid" => 'eee'];
            // } else {

            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . config('wechat.mini_program.default.app_id') . "&secret=" . config('wechat.mini_program.default.secret') . "&js_code=" . $code . "&grant_type=authorization_code";
            $token_json  = file_get_contents($url);

            Log::debug(["token_json", $token_json]);


            $token_data = json_decode($token_json, true);
            if (isset($token_data['errcode']) && $token_data['errcode']) {
                return success([
                    'code' => 40163,
                    'appid' => config('wechat.mini_program.default.app_id'),
                    'message' => $token_data
                ]);
            }


            $redis_key = "wx_session_key_" . $token_data["openid"];
            Redis::setex($redis_key, (86400 * 7), $token_data['session_key']);
            // }

            $result = MiniprogramhUser::where('openid', $token_data["openid"])->first();
            if (!$result) {
                $result = MiniprogramhUser::create(["openid" => $token_data["openid"]]);
            }

            $user = MiniprogramhUser::where('id', $result->id)->first();
            $token = auth('miniprogram')->login($user);



            if ($token) {
                return $this->respondWithToken($token, $token_json);
            } else {
                success(['code' => 10002, 'message' => 'token 生成失败']);
            }
        }
    }


    /**
     * web app 用户信息
     *
     * @return void
     */
    function me()
    {
        $data = auth('miniprogram')->user();
        if ($data) {
            $data['memberInfo'] = Member::where("openid", $data["openid"])->first();
        }
        return success($data);
    }


    function respondWithToken($token, $token_json)
    {
        return success([
            'access_token' => $token,
            // 'token_json' => $token_json,
            'token_type' => 'bearer',
            'expires_in' => JWTAuth::factory()->getTTL() * 60
        ]);
    }

    /**
     * 获取微信手机号
     * method： get
     * countryCode: "86"
     *  phoneNumber: "1308***301"
     *  purePhoneNumber: "1308***1301"
     */
    function getPhoneNumber(Request $request)
    {
        $params = $request->all();
        $openid = $request->user()->openid;
        $data = (new \App\Helper\Miniprogram())->getPhoneNumber($params, $openid);
        // Log::debug('getPhoneNumber-result', [$data]);
        if (isset($data['phoneNumber'])) {
            $data['phoneNumber'] = AES::encode($data['phoneNumber']);
            $data['purePhoneNumber'] = AES::encode($data['purePhoneNumber']);
        }
        Log::debug('getPhoneNumber_data', [$data]);
        return $this->success($data);
    }
}
